package com.ttj.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.ttj.domain.oracle.OrderInstock;
import com.ttj.domain.oracle.OrderRec;
import com.ttj.domain.oracle.OrderRecDetail;
import com.ttj.domain.oracle.WebUser;
import com.ttj.mapper.oracle.OrderInstockMapper;
import com.ttj.mapper.oracle.OrderRecMapper;
import com.ttj.service.OrderRecDetailService;
import com.ttj.service.OrderRecService;
import com.ttj.util.BeanUtil;
import com.ttj.vo.BaseRes;
import com.ttj.vo.OrderRecVo;

/**
 * 回收订单模块
 * 
 * @author ASia
 *
 */
@Service
public class OrderRecServiceImpl implements OrderRecService {

	@Resource
	private OrderRecMapper orderRecMapper;

	@Resource
	private OrderInstockMapper orderInstockMapper;

	@Resource
	private OrderRecDetailService detailService;

	@Resource
	private WebUserServiceImpl webUserServiceImpl;

	@Override
	public BaseRes<OrderRecVo> index(String username) {
		int unCheckNum = this.unCheck(username);
		int replyedNum = this.replyed(username);
		OrderRecVo recVo = new OrderRecVo();
		recVo.setUncheckNum(unCheckNum);
		recVo.setReplyedNum(replyedNum);
		BaseRes<OrderRecVo> baseRes = new BaseRes<OrderRecVo>();
		baseRes.setData(recVo);
		return baseRes;
	}

	@Override
	public int unCheck(String rperson) {
		return orderRecMapper.unCheck(rperson);
	}

	@Override
	public int replyed(String rperson) {
		return orderRecMapper.replyed(rperson);
	}

	@Override
	public BaseRes<List<OrderRec>> orderRecList(String username, Integer oStatus) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("oStatus", oStatus);
		map.put("rperson", username);
		List<OrderRec> recList = orderRecMapper.orderRecList(map);
		int recListCount = orderRecMapper.orderRecListCount(map);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		BaseRes<List<OrderRec>> baseRes = new BaseRes<List<OrderRec>>();
		for (OrderRec orderRec : recList) {
			String addr = orderRec.getAddr() == null
					|| orderRec.getAddr().length() < 8 ? orderRec.getAddr()
					: orderRec.getAddr().substring(8);
			String oindate = orderRec.getoIndate() == null ? "" : sdf
					.format(orderRec.getoIndate());// 回收订单创建时间
			String predictTime = orderRec.getPredictTime() == null ? "" : sdf
					.format(orderRec.getPredictTime());// 回收订单预计上门时间
			String rDate = orderRec.getrDate() == null ? "" : sdf
					.format(orderRec.getrDate());// 回收订单应答时间
			orderRec.setOindate(oindate);
			if (predictTime != "") {
				orderRec.setPredictDate(predictTime);
			}
			if (rDate != "") {
				orderRec.setRdate(rDate);
			}
			orderRec.setAddr(addr);
		}
		baseRes.setData(BeanUtil.voConvertList(recList, OrderRec.class));
		baseRes.setTotalCount(recListCount);
		return baseRes;
	}

	@Override
	public int reply(Long orderId, String replyTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DATE);
		int ss = calendar.get(Calendar.MINUTE);
		Date repTime = null;
		try {
			repTime = sdf.parse(year + "-" + month + "-" + day + " "
					+ replyTime + ":" + ss);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		map.put("orderId", orderId);
		map.put("repTime", repTime);
		return orderRecMapper.reply(map);
	}

	@Override
	public BaseRes<List<OrderRec>> orderRecListCompleted(String username) {
		List<OrderRec> recListCompleted = orderRecMapper
				.orderRecListCompleted(username);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		for (OrderRec orderRec : recListCompleted) {
			String addr = orderRec.getAddr() == null
					|| orderRec.getAddr().length() < 8 ? orderRec.getAddr()
					: orderRec.getAddr().substring(8);
			String lCTime = orderRec.getlCTime() == null ? "" : sdf
					.format(orderRec.getlCTime());// 回收订单收货完成时间
			if (lCTime != "") {
				orderRec.setLcdate(lCTime);
			}
			orderRec.setAddr(addr);
		}
		BaseRes<List<OrderRec>> baseRes = new BaseRes<List<OrderRec>>();
		baseRes.setData(recListCompleted);
		return baseRes;
	}

	@Override
	public BaseRes<List<OrderRecVo>> getOrderRecDetail(Long orderId) {
		List<OrderRecVo> recDetail = orderRecMapper.getOrderRecDetail(orderId);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		for (OrderRec orderRec : recDetail) {
			String addr = orderRec.getAddr() == null
					|| orderRec.getAddr().length() < 8 ? orderRec.getAddr()
					: orderRec.getAddr().substring(8);
			String oindate = orderRec.getoIndate() == null ? "" : sdf
					.format(orderRec.getoIndate());// 回收订单创建时间
			String rDate = orderRec.getrDate() == null ? "" : sdf
					.format(orderRec.getrDate());// 回收订单应答时间
			String lCTime = orderRec.getlCTime() == null ? "" : sdf
					.format(orderRec.getlCTime());// 回收订单收货完成时间
			orderRec.setRdate(rDate);// 回收订单应答时间
			orderRec.setLcdate(lCTime);// 回收订单收货完成时间
			orderRec.setOindate(oindate);// 回收订单创建时间
			orderRec.setAddr(addr);// 地址
		}
		BaseRes<List<OrderRecVo>> baseRes = new BaseRes<List<OrderRecVo>>();
		baseRes.setData(recDetail);
		return baseRes;
	}

	@Override
	public BaseRes<List<OrderRecVo>> getOrderRecDetailList(Long orderId) {
		List<OrderRecVo> recDetailList = orderRecMapper
				.getOrderRecDetailList(orderId);
		BaseRes<List<OrderRecVo>> baseRes = new BaseRes<List<OrderRecVo>>();
		baseRes.setData(recDetailList);
		return baseRes;
	}

	@Override
	public int callCount(Map<String, Object> map) {
		return orderRecMapper.callCount(map);
	}

	@Override
	public int recycleCount(Map<String, Object> map) {
		return orderRecMapper.recycleCount(map);
	}

	@Override
	public double deposit(Map<String, Object> map) {
		return orderRecMapper.deposit(map);
	}

	@Override
	public double cash(Map<String, Object> map) {
		return orderRecMapper.cash(map);
	}

	@Override
	public double recycleNum1(Map<String, Object> map) {
		return orderRecMapper.recycleNum1(map);
	}

	@Override
	public int recycleNum2(Map<String, Object> map) {
		return orderRecMapper.recycleNum2(map);
	}

	@Override
	public int repeal(Map<String, Object> map) {
		return orderRecMapper.repeal(map);
	}

	@Override
	public BaseRes<Map<String, Object>> dailylog(String username,
			String begintime, String endtime) {
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		map.put("rperson", username);
		map.put("beginTime", begintime);
		map.put("endTime", endtime);
		// 工作日志
		map1.put("callCount", orderRecMapper.callCount(map));
		map1.put("recycleCount", orderRecMapper.recycleCount(map));
		map1.put("deposit", orderRecMapper.deposit(map));
		map1.put("cash", orderRecMapper.cash(map));
		map1.put("recycleNum1", orderRecMapper.recycleNum1(map));
		map1.put("recycleNum2", orderRecMapper.recycleNum2(map));
		map1.put("repeal", orderRecMapper.repeal(map));
		map1.put("newUsers", orderRecMapper.newUsers(map));
		map1.put("goodEvaluateNum", orderRecMapper.goodEvaluateNum(map));
		map1.put("badEvaluateNum", orderRecMapper.badEvaluateNum(map));
		map1.put("checkNum1", orderInstockMapper.checkNum1(map));
		map1.put("checkNum2", orderInstockMapper.checkNum2(map));
		map1.put("hangupNum", orderInstockMapper.hangupNum(map));
		// 折叠层
		List<OrderRec> timeOutReply = orderRecMapper.timeOutReply(map);
		for (OrderRec orderRecVo : timeOutReply) {
			orderRecVo.setOindate(sdf.format(orderRecVo.getoIndate()));
			orderRecVo.setRdate(sdf.format(orderRecVo.getrDate()));
		}
		List<OrderRec> timeOutFinish = orderRecMapper.timeOutFinish(map);
		for (OrderRec orderRecVo : timeOutFinish) {
			orderRecVo.setOindate(sdf.format(orderRecVo.getoIndate()));
			orderRecVo.setLcdate(sdf.format(orderRecVo.getlCTime()));
		}
		List<OrderRec> recycleDetail = orderRecMapper.recycleDetail(map);
		List<OrderInstock> checkDetail = orderInstockMapper.checkDetail(map);
		map1.put("timeOutReply", timeOutReply);
		map1.put("timeOutFinish", timeOutFinish);
		map1.put("recycleDetail", recycleDetail);
		map1.put("checkDetail", checkDetail);
		BaseRes<Map<String, Object>> baseRes = new BaseRes<Map<String, Object>>();
		baseRes.setData(map1);
		return baseRes;
	}

	@Override
	public int newUsers(Map<String, Object> map) {
		return orderRecMapper.newUsers(map);
	}

	@Override
	public int goodEvaluateNum(Map<String, Object> map) {
		return orderRecMapper.goodEvaluateNum(map);
	}

	@Override
	public int badEvaluateNum(Map<String, Object> map) {
		return orderRecMapper.badEvaluateNum(map);
	}

	@Override
	public Map<String, Object> createRec(OrderRecVo recList) {
		Map<String, Object> map = new HashMap<String, Object>();
		OrderRecVo recVo = BeanUtil.voConvert(recList, OrderRecVo.class);// 数据来源
		Date now = new Date();
		double price = 0;// 订单总价
		// **************处理品类数据****************//
		String detailList = recVo.getDetailList();
		Gson gson = new Gson();
		JsonParser jp = new JsonParser();
		JsonArray parse = jp.parse(detailList).getAsJsonArray();
		List<OrderRecDetail> list = new ArrayList<OrderRecDetail>();// 获取详情集合
		for (JsonElement detail : parse) {
			OrderRecDetail recDetail = gson.fromJson(detail,OrderRecDetail.class);
			price += recDetail.getTotal();
			list.add(recDetail);
		}
		// ******************************//
		OrderRec rec = new OrderRec();// 储存数据
		OrderRec ids = orderRecMapper.getId();// id、orderId
		String creater = recVo.getCreater();// 创建者
		// 获取收购员信息

		WebUser user = new WebUser();
		Integer id = ids.getId();// 最后一个ID
		Long orderId = ids.getOrderId();// 最后一个orderId
		int type = recVo.getType();// 创建类型 0->匿名 1->条形码 2->手机号
		Integer payMethod = recVo.getPayMethod();// 支付方式
		String comments = recVo.getComments() == null ? "" : recVo
				.getComments();// 备注
		// String lPhone = recVo.getlPhone()==null?"":recVo.getlPhone();//收货人电话
		String cname = recVo.getCname() == null ? "" : recVo.getCname();// 匿名
		String addr = recVo.getAddr() == null ? "" : recVo.getAddr();// 客户地址
		int orderWeight = 0;
		double total = recVo.getTotal() == 0 ? 0 : recVo.getTotal();
		rec.setId(id + 1);
		rec.setOrderId(orderId + 1);
		rec.setPayMethod(payMethod);
		rec.setComments(comments);
		rec.setPrice(price * 100);
		rec.setoIndate(now);
		rec.setfJAuthor(creater);
		rec.setfJMoney(price * 100);
		rec.setOrderMoney(price * 100);
		rec.setfJTime(now);
		rec.setlCTime(now);
		rec.setlAuthor(creater);
		rec.setoAuthor(creater);
		rec.setrDate(now);
		rec.setRperson(creater);
		rec.setModifTime(now);
		for (OrderRecDetail orderRecDetail : list) {
			detailService.createDetail(orderId + 1, orderRecDetail);
			int uint = orderRecDetail.getUint();
			if (uint == 0) {
				orderWeight += orderRecDetail.getNum();
			}
		}
		if (type == 0) {
			rec.setCname(cname);
			rec.setAddr(addr);
		}
		if (type == 1) { // 条形码
			String barcode = recVo.getBarcode();
			BaseRes<WebUser> baseRes = webUserServiceImpl
					.getUser(type, barcode);
			user = baseRes.getData();
			// 查询用户信息
			String name = user.getName() == null ? user.getPhonenum() : user
					.getName();
			String useraddr = user.getUseraddr() == null ? "" : user
					.getUseraddr();
			String phonenum = user.getPhonenum() == null ? "" : user
					.getPhonenum();
			rec.setCphone(phonenum);
			rec.setCperson(name);
			rec.setAddr(useraddr);
			webUserServiceImpl.updUser(total, user,
					orderWeight + user.getSellnum());
		}
		if (type == 2) { // 手机号
			String cphone = recVo.getCphone();// 客户手机号
			BaseRes<WebUser> baseRes = webUserServiceImpl.getUser(type, cphone);
			user = baseRes.getData();
			// 查询用户信息
			String name = user.getName() == null ? user.getPhonenum() : user
					.getName();
			String useraddr = user.getUseraddr() == null ? "" : user
					.getUseraddr();
			String phonenum = user.getPhonenum() == null ? "" : user
					.getPhonenum();
			rec.setCphone(phonenum);
			rec.setCperson(name);
			rec.setAddr(useraddr);
			webUserServiceImpl.updUser(total, user,
					orderWeight + user.getSellnum());
		}
		orderRecMapper.createRec(rec);
		map.put("res", "回收完成");
		return map;
	}

	@Override
	public Map<String, Object> updateRec(OrderRecVo recList) {
		Map<String, Object> map = new HashMap<String, Object>();
		OrderRecVo recVo = BeanUtil.voConvert(recList, OrderRecVo.class);// 数据来源

		double price = 0;// 订单总价
		String detailList = recVo.getDetailList();
		Gson gson = new Gson();
		JsonParser jp = new JsonParser();
		JsonArray parse = jp.parse(detailList).getAsJsonArray();
		List<OrderRecDetail> list = new ArrayList<OrderRecDetail>();// 获取详情集合
		for (JsonElement detail : parse) {
			OrderRecDetail recDetail = gson.fromJson(detail,
					OrderRecDetail.class);
			price += recDetail.getTotal();
			list.add(recDetail);
		}

		Date now = new Date();
		OrderRec rec = new OrderRec();// 储存数据
		Long orderId = recVo.getOrderId();// 订单orderId
		Integer payMethod = recVo.getPayMethod();// 支付方式
		String creater = recVo.getCreater();// 创建者
		int type = recVo.getType();
		double total = recVo.getTotal() == 0 ? 0 : recVo.getTotal();
		rec.setOrderId(orderId);
		rec.setPrice(price * 100);
		rec.setPayMethod(payMethod);
		rec.setfJsTime(now);
		rec.setfJAuthor(creater);
		rec.setfJMoney(price * 100);
		rec.setOrderMoney(price * 100);
		rec.setfJTime(now);
		rec.setlCTime(now);
		rec.setlAuthor(creater);
		rec.setModifTime(now);
		int orderWeight = 0;
		for (OrderRecDetail orderRecDetail : list) {
			detailService.createDetail(orderId, orderRecDetail);
			int uint = orderRecDetail.getUint();
			if (uint == 0) {
				orderWeight += orderRecDetail.getNum();
			}
		}
		String cphone = recVo.getCphone();// 客户手机号
		BaseRes<WebUser> baseRes = webUserServiceImpl.getUser(type, cphone);// 获取客户数据
		WebUser user = baseRes.getData();
		webUserServiceImpl
				.updUser(total, user, orderWeight + user.getSellnum());// 修改客户数据
		orderRecMapper.updateRec(rec);
		map.put("res", "回收完成");
		return map;
	}

}
